package pm

import (
	"context"
	"itam/internal/dao"
	"itam/internal/model"
	"itam/internal/service"
)

type sPm struct{}

func init() {
	service.RegisterPm(New())
}

func New() *sPm {
	return &sPm{}
}

// Create 创建
func (s *sPm) Create(ctx context.Context, in model.PmCreateInput) (out model.PmCreateOutput, err error) {
	pmId, err := dao.Pm.Ctx(ctx).Data(in).InsertAndGetId()
	if err != nil {
		return out, err
	}
	return model.PmCreateOutput{Id: int(pmId)}, nil
}

// Delete 删除
func (s *sPm) Delete(ctx context.Context, id int) (err error) {
	_, err = dao.Pm.Ctx(ctx).Where(dao.Pm.Columns().Id, id).Delete()
	return
}

// Update 修改
func (s *sPm) Update(ctx context.Context, in model.PmUpdateInput) (err error) {
	_, err = dao.Pm.Ctx(ctx).Data(in).FieldsEx(dao.Pm.Columns().Id).Where(dao.Pm.Columns().Id, in.Id).Update()
	return err
}

// 列表查询
func (s *sPm) GetList(ctx context.Context, in model.PmGetListInput) (out *model.PmGetListOutput, err error) {
	var m = dao.Pm.Ctx(ctx)
	out = &model.PmGetListOutput{
		List: make([]model.PmGetListOutputItem, 0),
		Page: in.Page,
		Size: in.Size,
	}
	if in.Brand != "" {
		m = m.WhereLike(dao.Pm.Columns().Brand, "%"+in.Brand+"%")
	}
	if in.IpAddress != "" {
		m = m.Where(dao.Pm.Columns().IpAddress, in.IpAddress)
	}
	if in.Model != "" {
		m = m.WhereLike(dao.Pm.Columns().Model, "%"+in.Model+"%")
	}
	if in.Owner != "" {
		m = m.WhereLike(dao.Pm.Columns().Owner, "%"+in.Owner+"%")
	}
	if in.RecomandStatus != "" {
		m = m.Where(dao.Pm.Columns().RecomandStatus, in.RecomandStatus)
	}
	if in.OsType != "" {
		m = m.Where(dao.Pm.Columns().OsType, in.OsType)
	}
	m = m.Page(in.Page, in.Size)
	m = m.OrderDesc(dao.Pm.Columns().Id)

	// 执行查询
	out.Total, err = m.Count()
	if err != nil {
		return out, err
	}
	if out.Total == 0 {
		return out, nil
	}
	err = m.Scan(&out.List)
	return
}

// detail
func (s *sPm) Detail(ctx context.Context, id int) (out *model.PmDetailOutput, err error) {
	// 虚拟机
	out = &model.PmDetailOutput{
		VmList: make([]model.PmDetailVmItem, 0),
	}
	var mv = dao.Vm.Ctx(ctx)
	mv = mv.Where(dao.Vm.Columns().PmId, id)
	err = mv.Scan(&out.VmList)
	return
}
